<template>
  <div class="users-container">
    <el-card class="header-card">
      <div class="header-content">
        <h2><el-icon><User /></el-icon> 用户管理</h2>
      </div>
    </el-card>

    <!-- 标签页切换 -->
    <el-card class="tabs-card">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="管理员" name="admin">
          <template #label>
            <span class="tab-label">
              <el-icon><UserFilled /></el-icon>
              管理员
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="普通用户" name="user">
          <template #label>
            <span class="tab-label">
              <el-icon><User /></el-icon>
              普通用户
            </span>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card v-loading="loading">
      <el-table :data="filteredUsers" stripe style="width: 100%; height: 600px;">
        <el-table-column prop="userId" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="nickname" label="昵称" min-width="100" />
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="phonenumber" label="手机号" width="120" />
        <el-table-column label="性别" width="80">
          <template #default="{ row }">
            {{ getSexText(row.sex) }}
          </template>
        </el-table-column>
        <el-table-column label="用户类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.userType === '0' ? 'danger' : 'success'">
              {{ row.userType === '0' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === '0' ? 'success' : 'danger'">
              {{ row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="showDialog" title="编辑用户" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" :disabled="isEdit" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="密码" :prop="isEdit ? '' : 'password'">
          <el-input v-model="form.password" type="password" :placeholder="isEdit ? '不修改请留空' : '请输入密码'" show-password />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.sex">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
            <el-radio label="2">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-radio-group v-model="form.userType">
            <el-radio label="0">管理员</el-radio>
            <el-radio label="1">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import type { User } from '@/types';
import { getAllUsers, getUsersByType, updateUser, deleteUser } from '@/api/user';
import { User as UserIcon, UserFilled } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';

const loading = ref(false);
const users = ref<User[]>([]);
const showDialog = ref(false);
const submitting = ref(false);
const formRef = ref<FormInstance>();
const isEdit = ref(false);
const activeTab = ref('admin');

const searchForm = reactive({
  username: ''
});

// 根据当前标签页过滤用户
const filteredUsers = computed(() => {
  if (activeTab.value === 'admin') {
    // 管理员：userType为'0'
    return users.value.filter(user => user.userType === '0');
  } else {
    // 普通用户：userType为'1'
    return users.value.filter(user => user.userType === '1');
  }
});

const form = reactive<User>({
  username: '',
  nickname: '',
  password: '',
  email: '',
  phonenumber: '',
  sex: '2',
  userType: '1',
  status: '0'
});

const rules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 30, message: '用户名长度在 3 到 30 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phonenumber: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
};

onMounted(() => {
  loadUsers();
});

const loadUsers = async () => {
  loading.value = true;
  try {
    const response = await getAllUsers();
    if (response.operateResult === 'SUCC' && response.data) {
      users.value = response.data;
    }
  } catch (error) {
    ElMessage.error('加载用户失败');
  } finally {
    loading.value = false;
  }
};

// 标签页切换
const handleTabChange = (tabName: string) => {
  activeTab.value = tabName;
  // 清空搜索条件
  searchForm.username = '';
};

const handleSearch = async () => {
  if (searchForm.username) {
    // 根据用户名搜索
    const allUsers = users.value;
    users.value = allUsers.filter(u => u.username.includes(searchForm.username));
  } else {
    // 重新加载所有用户
    await loadUsers();
  }
};

const handleReset = () => {
  searchForm.username = '';
  loadUsers();
};

const getSexText = (sex?: string) => {
  const sexMap: Record<string, string> = {
    '0': '男',
    '1': '女',
    '2': '未知'
  };
  return sexMap[sex || '2'] || '未知';
};


const handleEdit = (user: User) => {
  isEdit.value = true;
  Object.assign(form, { ...user, password: '' });
  showDialog.value = true;
};

const resetForm = () => {
  Object.assign(form, {
    username: '',
    nickname: '',
    password: '',
    email: '',
    phonenumber: '',
    sex: '2',
    userType: '1',
    status: '0'
  });
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        const updateData = { ...form };
        if (!updateData.password) {
          // 如果密码为空，使用原密码
          const originalUser = users.value.find(u => u.userId === form.userId);
          updateData.password = originalUser?.password || '';
        }
        const response = await updateUser(form.userId!, updateData);

        if (response.operateResult === 'SUCC') {
          ElMessage.success('更新成功');
          showDialog.value = false;
          loadUsers();
        } else {
          ElMessage.error(response.errorMsg || '操作失败');
        }
      } catch (error: any) {
        ElMessage.error(error.message || '操作失败');
      } finally {
        submitting.value = false;
      }
    }
  });
};

const handleDelete = (user: User) => {
  ElMessageBox.confirm(`确定要删除用户 "${user.username}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteUser(user.userId!);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('删除成功');
        loadUsers();
      } else {
        ElMessage.error(response.errorMsg || '删除失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '删除失败');
    }
  }).catch(() => {});
};
</script>

<style scoped>
.users-container {
  max-width: 1600px;
  margin: 0 auto;
  animation: fadeIn 0.5s ease-out;
  position: relative;
  z-index: 1;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #303133;
}

.tabs-card {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

/* 标签页样式 */
:deep(.el-tabs) {
  background: transparent;
}

:deep(.el-tabs__header) {
  margin: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(248, 250, 252, 0.9) 100%);
  border-radius: 12px;
  padding: 8px 20px;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0;
}

:deep(.el-tabs__nav) {
  border: none;
}

:deep(.el-tabs__item) {
  border: none;
  border-radius: 8px;
  margin: 8px 4px;
  padding: 0 32px;
  height: 48px;
  line-height: 48px;
  font-weight: 600;
  transition: all 0.3s ease;
  background: transparent;
  min-width: 140px;
  text-align: center;
}

:deep(.el-tabs__item:hover) {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
}

:deep(.el-tabs__item.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

:deep(.el-tabs__active-bar) {
  display: none;
}

.tab-label {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
}

/* 美化卡片样式 */
:deep(.el-card) {
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: none;
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.9);
}

/* 美化按钮样式 */
:deep(.el-button) {
  border-radius: 12px;
  font-weight: 600;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(245, 101, 101, 0.3);
}

:deep(.el-button--danger:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(245, 101, 101, 0.4);
}

/* 美化表格样式 */
:deep(.el-table) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

:deep(.el-table__header) {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

:deep(.el-table th) {
  background: transparent;
  color: #4a5568;
  font-weight: 600;
  border-bottom: 2px solid #e2e8f0;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f1f5f9;
}

:deep(.el-table tr:hover > td) {
  background-color: rgba(102, 126, 234, 0.05);
}

/* 美化标签样式 */
:deep(.el-tag) {
  border-radius: 8px;
  font-weight: 600;
  border: none;
}

:deep(.el-tag--success) {
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
  color: white;
}

:deep(.el-tag--danger) {
  background: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
  color: white;
}

/* 美化输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 美化模态框样式 */
:deep(.el-dialog) {
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
  border: none;
  backdrop-filter: blur(20px);
  background: rgba(255, 255, 255, 0.95);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 20px 20px 0 0;
  padding: 20px 24px;
  margin: 0;
}

:deep(.el-dialog__title) {
  font-weight: 700;
  font-size: 18px;
}

:deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 24px;
  color: white;
}

:deep(.el-dialog__body) {
  padding: 32px 24px;
  background: rgba(255, 255, 255, 0.8);
}
</style>

